import {
  Controller,
  Get,
  Post,
  Put,
  Body,
  Param,
  Query,
  Delete,
} from '@nestjs/common';
import { UserService } from './user.service';
import { User } from '../entities/user.entity';

interface CreateUserDto {
  name: string;
  phone: string;
  skuIds?: number[];
}

interface UserResponseDto {
  id: number;
  name: string;
  phone: string;
  createdAt: string;
  skus: { id: number; title: string }[];
}

interface FindAllResponseDto {
  data: UserResponseDto[];
  total: number;
}

interface UpdateUserDto {
  name?: string;
  phone?: string;
  skuIds?: number[];
}

@Controller('users')
export class UserController {
  constructor(private readonly userService: UserService) {}

  @Post()
  async create(@Body() createUserDto: CreateUserDto): Promise<User> {
    return await this.userService.create(createUserDto);
  }

  @Put(':id')
  async update(
    @Param('id') id: number,
    @Body() updateUserDto: UpdateUserDto,
  ): Promise<User> {
    return await this.userService.update(id, updateUserDto);
  }

  @Get()
  async findAll(
    @Query('name') name?: string,
    @Query('phone') phone?: string,
    @Query('skuId') skuId?: number,
    @Query('page') page?: number,
    @Query('size') size?: number,
  ): Promise<FindAllResponseDto> {
    const result = await this.userService.findAll({
      name,
      phone,
      skuId,
      page,
      size,
    });
    return {
      data: result.data.map((user) => ({
        id: user.id,
        name: user.name,
        phone: user.phone,
        createdAt: user.createdAt.toISOString().split('T')[0],
        skus: user.skus.map((sku) => ({
          id: sku.id,
          title: sku.title,
        })),
      })),
      total: result.total,
    };
  }

  @Delete(':id')
  async remove(@Param('id') id: number): Promise<void> {
    await this.userService.remove(id);
  }
}
